<span id="dynamic-subtitle"></span>

<script is:inline>
  const subtitles = ["Fuel", "Develop", "Monetize", "Harness"];
  let index = 0;
  let charIndex = 0;
  let isDeleting = false;
  let intervalId;

  function updateSubtitle() {
    const subtitleElement = document.getElementById("dynamic-subtitle");
    if (!subtitleElement) return;

    const currentWord = subtitles[index];

    // Update the text content with styling
    if (isDeleting) {
      subtitleElement.innerHTML = `<span style="color: #FF5733; font-weight: bold;">${currentWord.substring(0, charIndex - 1)}</span>`;
      charIndex--;
    } else {
      subtitleElement.innerHTML = `<span style="color: #FF5733; font-weight: bold;">${currentWord.substring(0, charIndex + 1)}</span>`;
      charIndex++;
    }

    // If the word is fully typed out
    if (!isDeleting && charIndex === currentWord.length) {
      setTimeout(() => {
        isDeleting = true;
      }, 1000); // Short pause before starting deletion
    }

    // If the word is fully deleted
    if (isDeleting && charIndex === 0) {
      isDeleting = false;
      index = (index + 1) % subtitles.length;
    }

    // Adjust typing speed (faster for deletion)
    const speed = isDeleting ? 50 : 150;
    intervalId = setTimeout(updateSubtitle, speed);
  }

  function initializeSubtitle() {
    // Clear any previous intervals to avoid overlapping
    clearTimeout(intervalId);

    index = 0;
    charIndex = 0;
    isDeleting = false;
    updateSubtitle(); // Start the typing effect
  }

  // Start the typing effect on initial load
  initializeSubtitle();

  // Reinitialize the subtitle effect after Astro page swap
  document.addEventListener("astro:after-swap", initializeSubtitle);

  // Optionally reinitialize the subtitle effect when the page becomes visible again
  document.addEventListener("visibilitychange", () => {
    if (!document.hidden) {
      initializeSubtitle();
    }
  });
</script>
